package com.jintian.smart.kernel.flowable.flowable.cmd;

import java.util.Date;

import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.CommentEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.task.Event;

public class AddHistoricCommentCmd implements Command<Void> {
    public static final int HistoricVariable_ProcessInstance = 0;
    public static final int HistoricVariable_TaskInstance = 1;
    public static final String varNamePrefix = "hi_varinst:";

    private final String processInstanceId;
    private final String taskId;
    private final String type;
    private final String action;
    private final String messaage;

    public AddHistoricCommentCmd(String processInstanceId, String taskId, String type, String action, String messaage) {
        this.taskId = taskId;
        this.processInstanceId = processInstanceId;
        this.messaage = messaage;
        this.type = type;
        this.action = action;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfiguration processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        // 历史备注表act_hi_comment 增加作废原因
        Date date = processEngineConfiguration.getClock().getCurrentTime();
        String userId = Authentication.getAuthenticatedUserId();
        CommentEntityManager commentManager = CommandContextUtil.getCommentEntityManager(commandContext);
        CommentEntity comment = CommandContextUtil.getCommentEntityManager(commandContext).create();
        comment.setUserId(userId);
        comment.setType(type);
        comment.setTime(date);
        comment.setTaskId(taskId);
        comment.setProcessInstanceId(processInstanceId);
        comment.setAction(action != null ? action : Event.ACTION_ADD_COMMENT);

        if (messaage != null) {
            String eventMessage = messaage.replaceAll("\\s+", " ");
            if (eventMessage.length() > 163) {
                eventMessage = eventMessage.substring(0, 160) + "...";
            }
            comment.setMessage(eventMessage);
            comment.setFullMessage(messaage);
        }
        commentManager.insert(comment);
        return null;
    }
}
